<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "6d134c3b"
    });
  daovoice('update');
  </script>




















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="Java虚拟机有三块组成部分，分别是：类装载子系统、运行时数据区、字节码执行引擎。运行时数据区是Java虚拟机内部的一个运行时内存，是性能调优的重点区域。身为Java工程师，必须要了解底层原理，才能从最根本上让机器发挥出应有的性能。">
<meta name="keywords" content="蓝士钦">
<meta property="og:type" content="article">
<meta property="og:title" content="Java虚拟机运行时数据区">
<meta property="og:url" content="https://www.lanshiqin.com/4cb4c29a/index.html">
<meta property="og:site_name" content="蓝士钦">
<meta property="og:description" content="Java虚拟机有三块组成部分，分别是：类装载子系统、运行时数据区、字节码执行引擎。运行时数据区是Java虚拟机内部的一个运行时内存，是性能调优的重点区域。身为Java工程师，必须要了解底层原理，才能从最根本上让机器发挥出应有的性能。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.lanshiqin.com/4cb4c29a/Java虚拟机运行时数据区.png">
<meta property="og:image" content="https://www.lanshiqin.com/4cb4c29a/Java虚拟机栈_栈帧.png">
<meta property="og:image" content="https://www.lanshiqin.com/4cb4c29a/堆内存划分.png">
<meta property="og:image" content="https://www.lanshiqin.com/4cb4c29a/Java虚拟机栈_栈帧02.png">
<meta property="og:image" content="https://www.lanshiqin.com/4cb4c29a/java虚拟机栈方法执行过程_1.gif">
<meta property="og:updated_time" content="2020-10-11T12:39:11.059Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java虚拟机运行时数据区">
<meta name="twitter:description" content="Java虚拟机有三块组成部分，分别是：类装载子系统、运行时数据区、字节码执行引擎。运行时数据区是Java虚拟机内部的一个运行时内存，是性能调优的重点区域。身为Java工程师，必须要了解底层原理，才能从最根本上让机器发挥出应有的性能。">
<meta name="twitter:image" content="https://www.lanshiqin.com/4cb4c29a/Java虚拟机运行时数据区.png">



  <link rel="alternate" href="/atom.xml" title="蓝士钦" type="application/atom+xml" />




  <link rel="canonical" href="https://www.lanshiqin.com/4cb4c29a/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Java虚拟机运行时数据区 | 蓝士钦</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

  <script src="/js/src/photoswipe.js?v="></script>
  <script src="/js/src/photoswipe-ui-default.js?v="></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蓝士钦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">编程是一种信仰</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-相册">
    <a href="/photos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />相册</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.lanshiqin.com/4cb4c29a/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="蓝士钦">
      <meta itemprop="description" content="编程是一种信仰">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蓝士钦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java虚拟机运行时数据区
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2020-10-05 22:26:28" itemprop="dateCreated datePublished" datetime="2020-10-05T22:26:28+08:00">2020-10-05</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2020-10-11 20:39:11" itemprop="dateModified" datetime="2020-10-11T20:39:11+08:00">2020-10-11</time>
              
            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Java虚拟机有三块组成部分，分别是：类装载子系统、运行时数据区、字节码执行引擎。运行时数据区是Java虚拟机内部的一个运行时内存，是性能调优的重点区域。身为Java工程师，必须要了解底层原理，才能从最根本上让机器发挥出应有的性能。<br><a id="more"></a></p>
<blockquote>
<p>本章分析的是JDK8的JVM运行时数据区，有关JVM数据区的文档可到Oracle官网进行查阅<br><a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5" target="_blank" rel="noopener">https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5</a></p>
</blockquote>
<h1 id="概念部分"><a href="#概念部分" class="headerlink" title="概念部分"></a>概念部分</h1><p>Java虚拟机定义了在程序执行期间使用的各种运行时数据区域。图中黄色区域是线程共享的，在虚拟机启动时创建，随着虚拟机的停止而销毁。图中绿色区域是线程私有的，随着线程的启动被分配，随着线程的停止而销毁。Java虚拟机运行时数据区主要分为5个部分：程序计数器、Java虚拟机栈、堆、方法区、本地方法栈。<br><img src="/4cb4c29a/Java虚拟机运行时数据区.png" title="Java虚拟机运行时数据区"></p>
<h2 id="程序计数器（Program-Counter-Register）"><a href="#程序计数器（Program-Counter-Register）" class="headerlink" title="程序计数器（Program Counter Register）"></a>程序计数器（Program Counter Register）</h2><p>线程私有区域，是一块较小的内存空间，用来记录当前线程所执行的字节码行号。每个线程都有自己的程序计数器，各个线程的程序计数器互不影响。<br>如果线程正在执行的是一个Java方法，则记录的是字节码的指令地址，如果执行的是本地方法，则计数器的值为空。此区域不会出现OOM的情况。</p>
<h2 id="Java虚拟机栈（Java-Virtual-Machine-Stack）"><a href="#Java虚拟机栈（Java-Virtual-Machine-Stack）" class="headerlink" title="Java虚拟机栈（Java Virtual Machine Stack）"></a>Java虚拟机栈（Java Virtual Machine Stack）</h2><p>线程私有区域，生命周期与线程相同。Java虚拟机栈描述的是Java方法执行时的内存模型，每个方法在执行时会在虚拟机栈中创建一个栈帧，进行入栈操作。栈帧内部包含4个区域：本地变量表、操作数栈、动态链接、方法出口。方法执行完毕会将栈帧出栈。<br><img src="/4cb4c29a/Java虚拟机栈_栈帧.png" title="Java虚拟机栈_栈帧"><br>在Java虚拟机规范中，此区域可能出现 StackOverflowError和 OutOfMemoryError。<br>比如在一个线程中方法调用的深度超出了Java虚拟机栈的大小，就无法为新的方法调用分配栈帧，抛出 StackOverflowError。<br>在多线程中为方法创建栈帧，每个线程为方法创建的栈大小总和超出了Java虚拟机栈的大小，无法为新的方法调用分配内存空间，就会抛出OutOfMemoryError。</p>
<h2 id="堆（Heap）"><a href="#堆（Heap）" class="headerlink" title="堆（Heap）"></a>堆（Heap）</h2><p>线程共享区域，在虚拟机启动时创建，用来存储对象实例，是JVM垃圾收集器的主要区域。<br>垃圾收集器为了更加高效的进行垃圾回收，采用了各种不同的垃圾回收算法，将堆内存进行划分。<br>在JDK1.8中，堆内存可以细分为：Eden区、Survivor区（From Survivor，To Survivor）、Old区。<br><img src="/4cb4c29a/堆内存划分.png" title="堆内存划分"><br>堆区在逻辑上是连续的内存区域，不要求物理内存连续。堆大小可以固定也设置成动态，可以通过JVM运行参数  -Xmx 和 -Xms 指定堆大小。如果堆中的内存无法满足分配要求将会抛出 OutOfMemoryError。<br>关于垃圾收集策略此处不展开分析，后面会专门写关于垃圾收集的文章。</p>
<h2 id="方法区（Method-Area）"><a href="#方法区（Method-Area）" class="headerlink" title="方法区（Method Area）"></a>方法区（Method Area）</h2><p>线程共享区域，在虚拟机启动时创建，用来存储类信息、常量、静态变量和及时编译后的代码等数据。<br>可以选择不进行垃圾收集。在JDK7中使用永久代来实现方法区，在JDK8中废弃了永久代采用Metaspace（元空间）来进行代替。<br>元空间在本地内存中。</p>
<p>在方法区中还包含了一个 运行时常量池（Runtime Constant Pool），用来存放各种字面量和符号引用，这些字面量不一定是在编译期产生，还可以是程序动态生成的，比如通过 String类的intern方法。<br>如果常量池中的内存无法满足分配要求，将会抛出 OutOfMemoryError。</p>
<h2 id="本地方法栈（Native-Method-Stacks）"><a href="#本地方法栈（Native-Method-Stacks）" class="headerlink" title="本地方法栈（Native Method Stacks）"></a>本地方法栈（Native Method Stacks）</h2><p>与Java虚拟机方法栈的作用类似，区别在于本地方法栈服务于Native方法，在Java中调用的Native方法都将由本地方法栈为方法分配内存，Java虚拟机并不要求本地方法栈中使用的语言和数据结构，在 HotSpot虚拟机中本地方法栈和Java虚拟机方法栈合二为一。 这个区域同样可能发生StackOverflowError和OutOfMemoryError。</p>
<h1 id="案例分析"><a href="#案例分析" class="headerlink" title="案例分析"></a>案例分析</h1><h2 id="一个方法的执行过程"><a href="#一个方法的执行过程" class="headerlink" title="一个方法的执行过程"></a>一个方法的执行过程</h2><blockquote>
<p>通过一个方法的执行过程，分析Java虚拟机栈内部工作流程</p>
</blockquote>
<p>编写如下代码，在一个Demo类中，包含一个main方法和一个compute方法<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">int</span> b = <span class="number">2</span>;</span><br><span class="line">        <span class="keyword">int</span> c =  a + b;</span><br><span class="line">        <span class="keyword">return</span> c * <span class="number">100</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Demo demo = <span class="keyword">new</span> Demo();</span><br><span class="line">        <span class="keyword">int</span> result = demo.compute();</span><br><span class="line">        System.out.println(<span class="string">"result="</span>+result);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>使用javac将代码编译成java字节码文件Demo.class<br>使用  vim -b Demo.class 打开文件，再使用 :%!xxd 以16进制查看文件，得到如下字节码指令<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">00000000: cafe babe 0000 0034 0030 0a00 0d00 1807  .......4.0......</span><br><span class="line">00000010: 0019 0a00 0200 180a 0002 001a 0900 1b00  ................</span><br><span class="line">00000020: 1c07 001d 0a00 0600 1808 001e 0a00 0600  ................</span><br><span class="line">00000030: 1f0a 0006 0020 0a00 0600 210a 0022 0023  ..... ....!..&quot;.#</span><br><span class="line">00000040: 0700 2401 0006 3c69 6e69 743e 0100 0328  ..$...&lt;init&gt;...(</span><br><span class="line">00000050: 2956 0100 0443 6f64 6501 000f 4c69 6e65  )V...Code...Line</span><br><span class="line">00000060: 4e75 6d62 6572 5461 626c 6501 0007 636f  NumberTable...co</span><br><span class="line">00000070: 6d70 7574 6501 0003 2829 4901 0004 6d61  mpute...()I...ma</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>这些字节码指令能够被JVM虚拟机执行，每个指令字符都有对应的解释，可以通过查阅Oracle官方的虚拟机字节码指令表进行对照。<br>本章不展开分析字节码，后续会写对应的文章分析字节码。<br>每个字节码指令都有对应的助记符，为了使人类更加易读，可以使用javap命令，将Demo.class 反汇编成等效的虚拟机指令助记符。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">javap -c Demo.class &gt; Demo.txt</span><br></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">Compiled from &quot;Demo.java&quot;</span><br><span class="line">public class com.lanshiqin.Demo &#123;</span><br><span class="line">  public com.lanshiqin.Demo();</span><br><span class="line">    Code:</span><br><span class="line">       0: aload_0</span><br><span class="line">       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V</span><br><span class="line">       4: return</span><br><span class="line"></span><br><span class="line">  public int compute();</span><br><span class="line">    Code:</span><br><span class="line">       0: iconst_1</span><br><span class="line">       1: istore_1</span><br><span class="line">       2: iconst_2</span><br><span class="line">       3: istore_2</span><br><span class="line">       4: iload_1</span><br><span class="line">       5: iload_2</span><br><span class="line">       6: iadd</span><br><span class="line">       7: istore_3</span><br><span class="line">       8: iload_3</span><br><span class="line">       9: bipush        100</span><br><span class="line">      11: imul</span><br><span class="line">      12: ireturn</span><br><span class="line"></span><br><span class="line">  public static void main(java.lang.String[]);</span><br><span class="line">    Code:</span><br><span class="line">       0: new           #2                  // class com/lanshiqin/Demo</span><br><span class="line">       3: dup</span><br><span class="line">       4: invokespecial #3                  // Method &quot;&lt;init&gt;&quot;:()V</span><br><span class="line">       7: astore_1</span><br><span class="line">       8: aload_1</span><br><span class="line">       9: invokevirtual #4                  // Method compute:()I</span><br><span class="line">      12: istore_2</span><br><span class="line">      13: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;</span><br><span class="line">      16: new           #6                  // class java/lang/StringBuilder</span><br><span class="line">      19: dup</span><br><span class="line">      20: invokespecial #7                  // Method java/lang/StringBuilder.&quot;&lt;init&gt;&quot;:()V</span><br><span class="line">      23: ldc           #8                  // String result=</span><br><span class="line">      25: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;</span><br><span class="line">      28: iload_2</span><br><span class="line">      29: invokevirtual #10                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;</span><br><span class="line">      32: invokevirtual #11                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;</span><br><span class="line">      35: invokevirtual #12                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V</span><br><span class="line">      38: return</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>每个方法在执行时，都会创建一个栈帧，该程序中有main方法和compute方法，在Java虚拟机中对应入下图<br><img src="/4cb4c29a/Java虚拟机栈_栈帧02.png" title="Java虚拟机栈_栈帧02"></p>
<p>字节码文件Demo.class被类装载子系统加载到JVM运行时数据区，做了一系列操作，这些操作此处不展开分析。<br>首先执行的是main方法，Java虚拟机栈对main方法进行入栈操作。<br>main方法中调用了compute方法，对compute进行入栈。<br>此处对compute方法的源代码和对应的字节码助记符详细的分析一下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> b = <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">int</span> c =  a + b;</span><br><span class="line">    <span class="keyword">return</span> c * <span class="number">100</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为了方便阅读，查阅了虚拟机字节码指令表，将对应助记符的含义注释在右侧<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public int compute();</span><br><span class="line">  Code:</span><br><span class="line">     0: iconst_1                 // 将int型1推送至栈顶</span><br><span class="line">     1: istore_1                 // 将栈顶int型数值存入第二个本地变量</span><br><span class="line">     2: iconst_2                 // 将int型2推送至栈顶 </span><br><span class="line">     3: istore_2                 // 将栈顶int型数值存入第三个本地变量</span><br><span class="line">     4: iload_1                  // 将第二个int型本地变量推送至栈顶</span><br><span class="line">     5: iload_2                  // 将第三个int型本地变量推送至栈顶</span><br><span class="line">     6: iadd                     // 将栈顶两个int型数值相加并将结果压入栈顶</span><br><span class="line">     7: istore_3                 // 将栈顶int型数值存入第四个本地变量</span><br><span class="line">     8: iload_3                  // 将第四个int型本地变量推送至栈顶</span><br><span class="line">     9: bipush        100        // 将单字节的常量值100 推送至栈顶</span><br><span class="line">    11: imul                     // 将栈顶两个int型数值相乘并将结果压入栈顶</span><br><span class="line">    12: ireturn                  // 从当前方法返回int</span><br></pre></td></tr></table></figure></p>
<p>可以看出字节码助记符还是很容易理解的，Code：底下每一行代表一个指令，指令前的数字可以当作指令行号来理解，程序计数器利用行号来记录当前执行到了哪一行。</p>
<p>为了便于理解，制作了执行过程的动画：<br><img src="/4cb4c29a/java虚拟机栈方法执行过程_1.gif" title="java虚拟机栈方法执行过程_1"></p>
<p>在compute方法被调用时，会创建computer的栈帧入栈到Java虚拟机栈中，此处省略方法入栈的演示。<br>ireturn指令，会返回当前操作数栈上的值300，方法执行完成后compute栈帧会出栈，此处省略方法出栈的演示。</p>
<p>将java源代码编译成class字节码后，就可以确定本地变量表的空间大小，compute栈帧中会创建对应大小的固定内存空间。有关虚拟机栈的详细内容此处不展开讨论，后续会有专门的文章进行分析。</p>
<h2 id="StackOverflowError"><a href="#StackOverflowError" class="headerlink" title="StackOverflowError"></a>StackOverflowError</h2><p>如果方法的调用深度超过Java虚拟机栈的大小，就会发生StackOverflowError。比如一个方法递归的调用自身，没有退出条件：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lanshiqin.jvm;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * HotSpot Java 虚拟机栈和本地方法栈溢出示例</span></span><br><span class="line"><span class="comment"> * StackOverflowError</span></span><br><span class="line"><span class="comment"> * VM Args：-Xss160k</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> 蓝士钦</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StackOF</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> stackLength = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stackLeak</span><span class="params">()</span></span>&#123;</span><br><span class="line">        stackLength ++;</span><br><span class="line">        stackLeak();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        StackOF stackOF = <span class="keyword">new</span> StackOF();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            stackOF.stackLeak();</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Throwable e)&#123;</span><br><span class="line">            System.out.println(<span class="string">"stack length:"</span> + stackOF.stackLength);</span><br><span class="line">            <span class="keyword">throw</span> e;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>错误信息如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">stack length:773</span><br><span class="line">Exception in thread &quot;main&quot; java.lang.StackOverflowError</span><br><span class="line">	at com.lanshiqin.jvm.StackOF.stackLeak(StackOF.java:14)</span><br><span class="line">	at com.lanshiqin.jvm.StackOF.stackLeak(StackOF.java:15)</span><br><span class="line">	at com.lanshiqin.jvm.StackOF.stackLeak(StackOF.java:15)</span><br><span class="line">	at com.lanshiqin.jvm.StackOF.stackLeak(StackOF.java:15)</span><br><span class="line">...</span><br><span class="line">... //  省略</span><br><span class="line">at com.lanshiqin.jvm.StackOF.main(StackOF.java:21)</span><br></pre></td></tr></table></figure></p>
<p>可以通过-Xss参数指定每个线程运行时的栈大小，栈越大能容纳的方法调用深度就越大。</p>
<h2 id="OutOfMemoryError"><a href="#OutOfMemoryError" class="headerlink" title="OutOfMemoryError"></a>OutOfMemoryError</h2><p>如果为每个线程分配过大的方法栈帧，则可能导致OOM，每个方法都占用很大的空间，在多线程执行时就会有很多个方法栈帧，Java虚拟机栈无法为新的方法分配内存空间，就会出现OOM。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lanshiqin.jvm;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Java 虚拟机栈和本地方法栈 多线程内存溢出示例</span></span><br><span class="line"><span class="comment"> * OutOfMemoryError,栈帧越大，越容易发生OOM</span></span><br><span class="line"><span class="comment"> * VM Args：-Xss100m</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> 蓝士钦</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">JavaVMStackOOM</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dontStop</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>)&#123;</span><br><span class="line">            <span class="comment">// 让方法不被销毁</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stackLeakByThread</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>)&#123;</span><br><span class="line">            Thread thread = <span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    dontStop();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            thread.start();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        JavaVMStackOOM javaVMStackOOM = <span class="keyword">new</span> JavaVMStackOOM();</span><br><span class="line">        javaVMStackOOM.stackLeakByThread();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个程序会创建无数个线程，可能会让操作系统假死，需要做好备份。<br>运行一段时间后，报错信息如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Exception in thread &quot;main&quot; java.lang.OutOfMemoryError: unable to create new native thread</span><br><span class="line">    at java.lang.Thread.start0(Native Method)</span><br><span class="line">    at java.lang.Thread.start(Thread.java:717)</span><br><span class="line">    at com.lanshiqin.jvm.JavaVMStackOOM.stackLeakByThread(JavaVMStackOOM.java:25)</span><br><span class="line">    at com.lanshiqin.jvm.JavaVMStackOOM.main(JavaVMStackOOM.java:31)</span><br><span class="line">Java HotSpot(TM) 64-Bit Server VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated</span><br></pre></td></tr></table></figure></p>
<p>大多数情况下，OOM  更多的是发生在堆内存分配，可以通过JVM参数 -Xms指定最小堆内存空间，-Xmx最大堆内存空间，当堆无法为新对象分配内存时，抛出OOM。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lanshiqin.jvm;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Java堆溢出示例</span></span><br><span class="line"><span class="comment"> * OutOfMemoryError</span></span><br><span class="line"><span class="comment"> * VM Args：-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./java_heap_dump.hprof</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> 蓝士钦</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HeapOOM</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">OOMObject</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        List&lt;OOMObject&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            list.add(<span class="keyword">new</span> OOMObject());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>错误信息如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">java.lang.OutOfMemoryError: Java heap space</span><br><span class="line">Dumping heap to ./java_heap_dump.hprof ...</span><br><span class="line">Unable to create ./java_heap_dump.hprof: File exists</span><br><span class="line">Exception in thread &quot;main&quot; java.lang.OutOfMemoryError: Java heap space</span><br><span class="line">    at java.util.Arrays.copyOf(Arrays.java:3210)</span><br><span class="line">    at java.util.Arrays.copyOf(Arrays.java:3181)</span><br><span class="line">    at java.util.ArrayList.grow(ArrayList.java:265)</span><br><span class="line">    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:239)</span><br><span class="line">    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:231)</span><br><span class="line">    at java.util.ArrayList.add(ArrayList.java:462)</span><br><span class="line">    at com.lanshiqin.jvm.HeapOOM.main(HeapOOM.java:20)</span><br></pre></td></tr></table></figure></p>
<p>本章对JVM运行时数据区做简单的概念分析，后续会更加底层的分析运行时的每个内存区域，转载请注明出处。</p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/8e86c433/index.html" rel="next" title="10x程序员工作法总结">
                <i class="fa fa-chevron-left"></i> 10x程序员工作法总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div id="gitalk-container"></div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="蓝士钦" />
            
              <p class="site-author-name" itemprop="name">蓝士钦</p>
              <p class="site-description motion-element" itemprop="description">编程是一种信仰</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/lanshiqin" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/l18120788756" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.jianshu.com/u/082f73dac819" target="_blank" title="JianShu"><i class="fa fa-fw fa-heartbeat"></i>JianShu</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:lanshiqin@outlook.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#概念部分"><span class="nav-number">1.</span> <span class="nav-text">概念部分</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#程序计数器（Program-Counter-Register）"><span class="nav-number">1.1.</span> <span class="nav-text">程序计数器（Program Counter Register）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java虚拟机栈（Java-Virtual-Machine-Stack）"><span class="nav-number">1.2.</span> <span class="nav-text">Java虚拟机栈（Java Virtual Machine Stack）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#堆（Heap）"><span class="nav-number">1.3.</span> <span class="nav-text">堆（Heap）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方法区（Method-Area）"><span class="nav-number">1.4.</span> <span class="nav-text">方法区（Method Area）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本地方法栈（Native-Method-Stacks）"><span class="nav-number">1.5.</span> <span class="nav-text">本地方法栈（Native Method Stacks）</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#案例分析"><span class="nav-number">2.</span> <span class="nav-text">案例分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一个方法的执行过程"><span class="nav-number">2.1.</span> <span class="nav-text">一个方法的执行过程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#StackOverflowError"><span class="nav-number">2.2.</span> <span class="nav-text">StackOverflowError</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#OutOfMemoryError"><span class="nav-number">2.3.</span> <span class="nav-text">OutOfMemoryError</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蓝士钦</span>

  

  
</div>










  <div class="footer-custom">闽ICP备15027850号</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>
<script src="/js/src/photoswipe.js?v="></script>
<script src="/js/src/photoswipe-ui-default.js?v="></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  










  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '08543e172f1359fce9c3',
          clientSecret: 'a8dd355f95e5035e0266c695e489fa991c9d28e2',
          repo: 'lanshiqin-blog',
          owner: 'lanshiqin',
          admin: ['lanshiqin'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')           
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
<!-- 页面点击小红心 --> 
<script type="text/javascript" src="/js/src/love.js"></script>
<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/crash_cheat.js"></script>